package com.heima.behavior.service.impl;

import com.heima.behavior.pojos.UserReadCount;
import com.heima.behavior.service.UserReadService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.behavior.dtos.ReadDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserReadServiceImpl implements UserReadService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 用户查查看文章后，增加文章阅读量，并保存到redis中
     * @param readDto
     * @return
     */
    @Override
    public ResponseResult readArticleCount(ReadDto readDto) {
        //1.参数校验
        if (readDto == null || readDto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.根据文章id，判断是否存在阅读数据
        //2.1获取文章id
        Long articleId = readDto.getArticleId();
        //2.2查询详情
        Query query = Query.query(Criteria.where("articleId").is(articleId));
        UserReadCount userReadCount = mongoTemplate.findOne(query, UserReadCount.class);

        //3.判断数据是否存在。存在修改数量，不存在新增数据
        if (userReadCount != null){
            int count = userReadCount.getCount();
            count = count + 1;
            userReadCount.setCount(count);
            mongoTemplate.save(userReadCount);
        }else {
            //4.不存在数据，封装新数据返回
            userReadCount = new UserReadCount();
            userReadCount.setArticleId(readDto.getArticleId());
            userReadCount.setCount(1);
            userReadCount.setCreatedTime(new Date());
            mongoTemplate.save(userReadCount);
        }
        //5.存储到redis中
        redisTemplate.opsForValue().set(BehaviorConstants.BEHAVIOR_READ+readDto.getArticleId(),userReadCount.getCount()+"");
        return ResponseResult.okResult("");
    }
}
